/**
 * Created by Administrator on 2015/1/26.
 */

var command = require('./command');
var utils = require('./utils');
var message = require('./message');
var Message = message.Message;
var logger = require('./logger');
var MongoBase = require('./mongoBase');
var Config = require('./config').Config();
var MongoCollection = require('./config').MongoCollection;


var rule = {
    text: "规则",
    command:"规则",
    regexStr: "规则",
    callback: function (jsonParam) {
        return utils.processEjsTemplate("rule", {});
    },
    check: function (command) {
        return 1;
    }
};


var help = {
    text: "帮助",
    command:"帮助",
    regexStr: "帮助",
    callback: function (jsonParam) {
        return command.allCommand();
    },
    check: function (command) {
        return 1;
    }
};


var newRoom = {
    text: "新游戏",
    command:"新游戏",
    regexStr: "新游戏%人类词语%魂词语",
    example:"新游戏%冰箱%空调",
    explan: "法官使用", //附加描述
    callback: function (jsonParam) {
        var input = jsonParam['Content'];
        var humanWord = input.split('%')[1];
        var soulWord = input.split('%')[2];
        if (humanWord.length != soulWord.length) {
            return Message.ILLEGAL_WORD_UNEUQAL;
        }
        var gameId = getUniqueGameId();
        var game = {
            gameId: gameId,
            createUser: jsonParam['FromUserName'],
            length: utils.calcWordLength(humanWord),
            time: utils.getNowTimeStr(),
            humanWord: humanWord,
            soulWord: soulWord,
            status: 0
        };
        MongoBase.updateOnlySync(MongoCollection.GAME, {createUser: jsonParam['FromUserName'], status: 1}, {status: 2});
        MongoBase.insertSync(MongoCollection.GAME, game);
        logger.info("房间创建成功", game);
        return Message.GAME_NEW_SUCCESS + game.gameId;
    },
    check: function (command) {
        return utils.splitCheck(command, 3);
    }
};


var getUniqueGameId = function () {
    var id = utils.generateGameID();
    var game = MongoBase.findManySync(MongoCollection.GAME, {"gameId": id});
    logger.debug("find game by id:" + id, game);
    if (game != undefined && game.length > 0) {
        getUniqueGameId();
        //return id;
    } else {
        return id;
    }
}


var getGameStatus = function (stat) {
    logger.debug("game  status ", stat)
    if (stat == 0) {
        return "新建";
    } else if (stat == 1) {
        return "进行中";
    }
    else if (stat == 2) {
        return "已结束";
    }
    else {
        return "异常状态";
    }
}

var status = {
    text: "游戏状态",
    command: "状态",
    regexStr: "状态%游戏号",
    example:"状态%N5YP",
    explan: "法官使用", //附加描述
    callback: function (jsonParam) {
        var input = jsonParam['Content'];
        var gameId = input.split('%')[1];
        var game = MongoBase.findOneSync(MongoCollection.GAME, {gameId: gameId});
        if (game == null) {
            return message.paraseMsg(Message.GAME_NOT_EXIST, [gameId])
        }

        var result = [];
        result[result.length] = "房间状态:" + getGameStatus(game.status);
        if (game.status == 2) {
            return result.join("");
        }
        var gameUsers = MongoBase.findManySync(MongoCollection.GAME_USERS, {gameId: gameId});
        if (gameUsers.length > 0) {
            result[result.length] = "已加入用户："
        } else {
            result[result.length] = "无用户加入"
        }
        for (var index in gameUsers) {
            var gameUser = gameUsers[index];
            var userOpenId = gameUser.userOpenId;
            var user = MongoBase.findOneSync(MongoCollection.USERS, {userOpenId: userOpenId});
            logger.debug("user.nickName", user['nickName']);
            var temp = user['nickName'];
            if (gameUser.role) {
                temp += "," + gameUser.role;
            }
            result[result.length] = temp;
        }

        return result.join("\n");
    },
    check: function (command) {
        return utils.splitCheck(command, 2);
    }
};

var joinGame = {
    text: "加入游戏",
    command: "加入",
    regexStr: "加入%游戏号",
    example:"加入%N5YP",
    explan: "玩家使用",
    callback: function (jsonParam) {
        var input = jsonParam['Content'];
        var userOpenId = jsonParam['FromUserName'];
        var gameId = input.split('%')[1];
        var game = MongoBase.findOneSync(MongoCollection.GAME, {gameId: gameId});
        if (game == null) {
            return message.paraseMsg(Message.GAME_NOT_EXIST, [gameId])
        }
        if (game['status'] == 1) {
            return Message.GAME_ALREAD_START;
        }
        if (game['status'] == 2) {
            return Message.GAME_ALREAD_END;
        }
        if (game['createUser'] == userOpenId) {
            return Message.CREATEUSER_CAN_NOT_JOIN;
        }
        var userOfGame = {gameId: gameId, userOpenId: userOpenId};
        MongoBase.updateOrInsertSync(MongoCollection.GAME_USERS, userOfGame, userOfGame);
        return message.paraseMsg(Message.JOIN_GAME_SUCCESS, [gameId]);
    },
    check: function (command) {
        return utils.splitCheck(command, 2);
    }
}

var nickNameCommand = {
    text: "昵称设置",    //命令描述
    command: "昵称", //实际命令，若无，则为命令描述【text】
    example:"昵称%兔斯基",
    regexStr: "昵称%你的昵称",  //命令使用方式，比如 加入%游戏号
    callback: function (jsonParam) {   //命令执行方法
        var input = jsonParam['Content'];
        var userOpenId = jsonParam['FromUserName'];
        var nickName = input.split('%')[1];
        var user = {
            userOpenId: userOpenId,
            nickName: nickName
        };
        MongoBase.updateOrInsertSync(MongoCollection.USERS, {userOpenId: userOpenId}, user);
        return message.paraseMsg(Message.NICKNAME_SET_SUCCESS, [nickName]);
    },
    check: function (command) { //命令输入的校验
        return utils.splitCheck(command, 2);
    }
}


exports.nickNameCommand = nickNameCommand;


var startGame = {
    text: "开始游戏",    //命令描述
    command: "开始", //实际命令，若无，则为命令描述【text】
    regexStr: "开始%游戏号",  //命令使用方式，比如 加入%游戏号
    example:"开始%N5YP",
    explan: "法官使用", //附加描述
    callback: function (jsonParam) {   //命令执行方法
        var input = jsonParam['Content'];
        var gameId = input.split('%')[1];
        var userOpenId = jsonParam['FromUserName'];
        var game = MongoBase.findOneSync(MongoCollection.GAME, {gameId: gameId});
        if (game == null) {
            return message.paraseMsg(Message.GAME_NOT_EXIST, [gameId])
        }
        if (game['status'] == 1) {
            return Message.GAME_STARTED;
        }
        if (game['status'] == 2) {
            return Message.GAME_ENDED;
        }
        if (game['createUser'] != userOpenId) {
            return Message.CREATEUSER_CAN_START;
        }
        var joinUsers = MongoBase.findManySync(MongoCollection.GAME_USERS, {gameId: gameId});
        if (joinUsers.length < 4 || joinUsers.length > 14) {
            return Message.USER_LIMIT;
        }
        roleUser(game, joinUsers); //随机给用户分配角色
        MongoBase.updateOrInsertSync(MongoCollection.GAME, {gameId: gameId}, {status: 1});
        return Message.GAME_STARTED;
    },
    check: function (command) { //命令输入的校验
        return utils.splitCheck(command, 2);
    }
};


var roleUser = function (game, joinUsers) {
    var count = joinUsers.length;
    var ghostCount = Math.floor(count / 3);
    var randomArray = [];
    for (var i = 0; i < count; i++) {
        randomArray.push(i);
    }
    randomArray.sort(function () {
        return 0.5 - Math.random();
    });
    logger.debug("randomArray ", randomArray);
    var soul = randomArray.slice(0, 1);
    var ghost = randomArray.slice(1, ghostCount + 1);
    var common = randomArray.slice(ghostCount + 1);
    updateUserRole(soul, joinUsers, game.soulWord, game);
    updateUserRole(ghost, joinUsers, "鬼(" + game.length + ")", game);
    updateUserRole(common, joinUsers, game.humanWord, game);
}

var updateUserRole = function (roleArray, joinUsers, role, game) {
    for (var i = 0; i < roleArray.length; i++) {
        var user = joinUsers[roleArray[i]];
        MongoBase.updateOnlySync(MongoCollection.GAME_USERS, {
            userOpenId: user.userOpenId,
            gameId: game.gameId
        }, {role: role})
    }
}


var sendRoleToUser = function (game) {
    var joinUsers = MongoBase.findManySync(MongoCollection.GAME_USERS, {gameId: game.gameId});
    for (var i = 0; i < joinUsers.length; i++) {
        var user = joinUsers[i];
        var jsonResult = {
            toUser: user.userOpenId,
            fromUser: Config.weixinUser,
            time: new Date().getTime(),
            content: user.role
        }
        logger.debug("jsonResult", jsonResult);
        var xmlResult = utils.processEjsTemplate(Config.replyText, jsonResult);
        logger.debug("xmlResult", xmlResult);
    }
}


var endGame = {
    text: "结束游戏",    //命令描述
    command: "结束", //实际命令，若无，则为命令描述【text】
    regexStr: "结束%游戏号",  //命令使用方式，比如 加入%游戏号
    example:"结束%N5YP",
    explan: "法官使用", //附加描述
    callback: function (jsonParam) {   //命令执行方法
        var input = jsonParam['Content'];
        var gameId = input.split('%')[1];
        var userOpenId = jsonParam['FromUserName'];
        var game = MongoBase.findOneSync(MongoCollection.GAME, {gameId: gameId});
        if (game == null) {
            return message.paraseMsg(Message.GAME_NOT_EXIST, [gameId])
        }
        if (game['status'] == 2) {
            return Message.GAME_ALREAD_END;
        }
        if (game['createUser'] != userOpenId) {
            return Message.CREATEUSER_CAN_END;
        }
        MongoBase.updateOrInsertSync(MongoCollection.GAME, {gameId: gameId}, {status: 2});
        return Message.GAME_ALREAD_END;
    },
    check: function (command) { //命令输入的校验
        return utils.splitCheck(command, 2);
    }
}


var myRole = {
    text: "获取我的角色",
    command: "角色",
    regexStr: "角色%游戏号",  //命令使用方式，比如 加入%游戏号
    example:"角色%N5YP",
    explan: "游戏开始后玩家使用", //附加描述
    callback: function (jsonParam) {
        var input = jsonParam['Content'];
        var gameId = input.split('%')[1];
        var userOpenId = jsonParam['FromUserName'];
        var game = MongoBase.findOneSync(MongoCollection.GAME, {gameId: gameId});
        if (game.createUser == userOpenId) {
            return Message.CREATEUSER_CAN_NOT_ROLE;
        }
        if (game.status != 1) {
            var status = getGameStatus(game.status)
            return message.paraseMsg(Message.GAME_HAS_ROLE_WHEN_ING, status);
        }
        var current = MongoBase.findOneSync(MongoCollection.GAME_USERS, {gameId: gameId, userOpenId: userOpenId});
        if (current == null) {
            return Message.GAME_NOT_HAVE_YOU;
        }
        return current.role;
    },
    check: function (command) { //命令输入的校验
        return utils.splitCheck(command, 2);
    }
}


command.register(nickNameCommand);
command.register(rule);
command.register(help);
command.register(newRoom);
command.register(startGame);
command.register(status);
command.register(joinGame);
command.register(myRole);
command.register(endGame);